<?php
/**
 * 借款申请处理model
 */
namespace app\v2\model;
use think\Model;
use  app\v2\model\UserBankCard;
use fuiou\FuiouApi;
use app\v2\model\UserOrder;
use app\v2\model\Order;
use app\v2\model\Apply;
use think\cache\driver\Redis;

class Fuiou extends Model {
    /**
     * [repay 还款]
     * @param  string &$no_order [description]
     * @param  string $phone     [description]
     * @return [type]            [description]
     */
    public function repay(&$no_order = '', $phone = '')
    {
        $userOrder = new UserOrder;
        $result = $userOrder->getOne(['no_order' => $no_order]);
        if(!$result)
        {
            $this->error = '订单不存在';
            return false;
        }
        if(!$result['bank_card_number'])
        {
            $this->error = '请先绑定银行卡';
            return false;
        }
        $userBankCard = new UserBankCard;
        $re =  $userBankCard->getCard(['bank_card_number' => $result['bank_card_number']],'user_nm,bind_mob,name');
        if(!$re)
        {
            $this->error = '此银行卡未签约';
            return false;
        }
        $data['orderno']   = $result['no_order'];//订单号
        $data['bankno']    = $re['user_nm'];//总行代码 
        $data['accntno']   = $result['bank_card_number'];//账号
        $data['accntnm']   = $re['name'];//账户名称
        $data['amt']       = $result['money_order'] * 100;//金额
        $data['certno']    = $result['id_no'];//证件号
        $data['mobile']    = $phone ?:$re['bind_mob'];//手机号
        $data['entseq']    = $result['apply_id'];//企业流水号
        $data['memo']      = '用户还款';//备注
        $data['projectid'] = $result['project_id'];//项目id
        $data['txncd']     = '09';//业务定义
        //请求支付
        $fuiouApi = new FuiouApi;
        $json = $fuiouApi->incomforreq($data);
        //支付结果
        $jsonRe = json_decode($json,true);
        if(!$jsonRe)
        {
            $this->error = '请求支付失败';
            return false;
        }
        file_put_contents(LOGS_DIR_NAME."repayResult_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:支付返回详情:".json_encode($jsonRe).'-订单号:'.$no_order."\n\n", FILE_APPEND);
        $order = new Order;
        $saveParam['pay_code'] = $jsonRe['ret'];
        $saveParam['pay_info'] = $jsonRe['memo'];
        $payRe = $order->allowField(true)->save($saveParam,['no_order' => $no_order]);
        if(!$payRe)
        {
            file_put_contents(LOGS_DIR_NAME."repayUpdateError_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:修改状态失败:-订单号:".$no_order."\n\n", FILE_APPEND);
        }
        if($jsonRe['ret'] != '000000')
        {
            $this->error = $jsonRe['memo'];
            return false;
        }
        
        //拼接参数结合之前的还款方式
        $datas['merchantOutOrderNo']  = $data['orderno'];
        $datas['payResult']  = '1';
        $datas['money_order']  = $data['amt'] / 100;
        $datas['pay_type']  = 'D';
        $res = $order->payAfter($datas, $phone);
        if(!$res)
        {
            file_put_contents(LOGS_DIR_NAME."repay_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:支付成功,修改订单失败,支付详情:".json_encode($datas)."\n\n", FILE_APPEND);
            $this->error = '支付成功,但订单修改失败,请联系客服人员,失败原因:'.$order->getError();
            return false;
        }
        return true;
    }
    /**
     * [recharge 充值]
     * @param  array  &$param [description]
     * @param  string $uid    [description]
     * @return [type]         [description]
     */
    public function recharge(&$param = [], $cardInfo = [])
    {
        if(!$cardInfo)
        {
            $this->error = '用户信息未找到';
            return false;
        }
        $redis = new Redis;
        $redis->select(config('redis_select'));
        if($redis->get('recharge:r'.$cardInfo['uid']))
        {
            $this->error = '请求支付中,请10秒后再试';
            return false;
        }
        //创建订单号
        $apply = new Apply;
        $no_order = $apply->order_number();

        //富友支付  项目录入
        $params['no_order'] = $no_order;
        $params['money_order'] = $param['money'];
        $params['order_number'] = $no_order;
        $params['phone'] = $cardInfo['bind_mob'];
        $order = new Order;
        //project参数
        $merge = array_merge($params,$cardInfo);
        $re = $order->getFuiouProjectParam($merge);
        $fuiouApi = new FuiouApi;
        $projectRes = $fuiouApi->project($re);
        $projectRes = json_decode($projectRes,true);
        //项目录入成功
        if($projectRes['ret'] != '0000')
        {
            $this->error = $projectRes['memo'];
            return false;
        }
        $merge['project_id'] = $projectRes['project_id'];
        $merge['money'] = $merge['money_order'];
        //自动写入字段
        $payRecharge= new PayRecharge();
        $res = $payRecharge->autoWrite($merge);
        if(!$res)
        {
            $this->error = '写入失败';
            return false;
        }

        $data['orderno']   = $no_order;//订单号
        $data['bankno']    = $cardInfo['user_nm'];//总行代码 
        $data['accntno']   = $cardInfo['bank_card_number'];//账号
        $data['accntnm']   = $cardInfo['name'];//账户名称
        $data['amt']       = $param['money'] * 100;//金额
        $data['certno']    = $cardInfo['id_card'];//证件号
        $data['mobile']    = $cardInfo['bind_mob'];//手机号
        $data['entseq']    = $no_order;//企业流水号
        $data['memo']      = '用户还款';//备注
        $data['projectid'] = $projectRes['project_id'];//项目id
        $data['txncd']     = '09';//业务定义
        //请求支付
        $fuiouApi = new FuiouApi;
        $json = $fuiouApi->incomforreq($data);
        //支付结果
        $jsonRe = json_decode($json,true);
        if(!$jsonRe)
        {
            $this->error = '请求支付失败';
            return false;
        }
        //未签约单独判断
        if($jsonRe['ret'] == '100011')
        {
            if($jsonRe['memo'] === '未签约')
            {
                $this->error = $jsonRe['memo'];
                return 'noContract';
            }
        }
        if($jsonRe['ret'] != '000000')
        {
            $this->error = $jsonRe['memo'];
            return false;
        }
        $datas['status'] = 1;
        $result = $payRecharge->autoWrite($datas, ['id' => $res->id]);
        
        if(!$result)
        {
            $this->error = '支付成功,修改状态失败';
            return false;
        }
        $redis->set('recharge:r'.$cardInfo['uid'],'1',10);
        return true;
    }
    /**
     * [handlerTimeOut 处理交易超时订单]
     * @param  string $order_number [description]
     * @return [type]               [description]
     */
    public function handlerTimeOut($order_number = '')
    {
        $userOrder = new UserOrder;
        $result = $userOrder->getOne(['no_order' => $order_number]);
        if(!$result)
        {
            $this->error = '订单不存在';
            return false;
        }
        $fuiouApi = new FuiouApi;
        $jsonRe = $fuiouApi->payResQuery($order_number,1);
        file_put_contents(LOGS_DIR_NAME."handlerTimtOut_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:".json_encode($jsonRe)."\n\n", FILE_APPEND);
        //支付结果
        if(!$jsonRe)
        {
            $this->error = '请求查询失败';
            return false;
        }
        if($jsonRe['trans'][0]['state'] != 1)
        {
            $this->error = $jsonRe['trans'][0]['result'];
            return false;
        }
        $order = new Order;
        $saveParam['pay_code'] = $jsonRe['ret'];
        $saveParam['pay_info'] = $jsonRe['memo'];
        $payRe = $order->allowField(true)->save($saveParam,['no_order' => $order_number]);
        if(!$payRe)
        {
            file_put_contents(LOGS_DIR_NAME."repayUpdateError_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:修改状态失败:-订单号:".$order_number."\n\n", FILE_APPEND);
        }
        if($jsonRe['ret'] != '000000')
        {
            $this->error = $jsonRe['memo'];
            return false;
        }
        
        //拼接参数结合之前的还款方式
        $datas['merchantOutOrderNo']  = $order_number;
        $datas['payResult']  = '1';
        $datas['money_order']  = $jsonRe['trans'][0]['amt'] / 100;
        $datas['pay_type']  = 'D';
        $res = $order->payAfter($datas);
        if(!$res)
        {
            file_put_contents(LOGS_DIR_NAME."repay_log.txt", '支付时间:'.date('Y-m-d H:i:s',time())." 结果:支付成功,修改订单失败,支付详情:".json_encode($datas)."\n\n", FILE_APPEND);
            $this->error = '支付成功,但订单修改失败,请联系客服人员,失败原因:'.$order->getError();
            return false;
        }
        return $jsonRe['trans'][0]['result'];
    }
}
